package com.steven.team.service

import com.alibaba.fastjson.JSONObject
import com.steven.team.pojo.MatchInfo
import com.steven.team.config.SpringWebSocketHandler
import com.steven.team.dao.TeamDao
import com.steven.team.pojo.TeamApply
import com.steven.team.pojo.TeamInfo
import com.steven.team.utils.ResultUtils.DELETE_ERROR
import com.steven.team.utils.ResultUtils.INSERT_ERROR
import com.steven.team.utils.ResultUtils.SELECT_ERROR
import com.steven.team.utils.ResultUtils.SUCCESS_CODE
import com.steven.team.utils.ResultUtils.UPDATE_ERROR
import com.steven.team.utils.makeRes
import org.springframework.beans.factory.annotation.Autowired
import org.springframework.stereotype.Service
import org.springframework.transaction.annotation.Transactional
import org.springframework.web.socket.TextMessage

@Service
open class TeamServiceImp : TeamService {

    @Autowired
    val teamDao: TeamDao? = null

    @Autowired
    val webSocketHandler: SpringWebSocketHandler? = null

    @Transactional
    override fun addTeam(uid: Long, matchId: Long, teamName: String, name: String, url: String): JSONObject {
        val json = JSONObject()
        return try {
            if (matchId > 0L) {
                val teamInfo = TeamInfo()
                teamInfo.belongUserId = uid
                teamInfo.createTime = System.currentTimeMillis()
                teamInfo.matchId = matchId
                teamInfo.teamName = teamName
                teamInfo.status = 0
                teamDao!!.addTeam(teamInfo)
            } else {
                val matchRes = teamDao!!.searchMatchByName(name).firstOrNull()
                val dbMatchId = if (matchRes != null) {
                    matchRes.id
                } else {
                    val matchInfo = MatchInfo()
                    matchInfo.setName(name).setUrl(url).setBelong("用户自创")
                    teamDao.addMatch(matchInfo)
                    matchInfo.id
                }
                val teamInfo = TeamInfo()
                teamInfo.belongUserId = uid
                teamInfo.createTime = System.currentTimeMillis()
                teamInfo.matchId = dbMatchId
                teamInfo.teamName = teamName
                teamInfo.status = 0
                teamDao.addTeam(teamInfo)
            }
            makeRes(SUCCESS_CODE, json)
        } catch (e: Exception) {
            json["msg"] = e.printStackTrace()
            makeRes(INSERT_ERROR, json)
        }
    }

    override fun updateTeamName(name: String, teamId: Long): JSONObject {
        val json = JSONObject()
        return try {
            teamDao!!.updateTeamName(name, teamId)
            makeRes(SUCCESS_CODE, json)
        } catch (e: Exception) {
            json["msg"] = e.printStackTrace()
            makeRes(UPDATE_ERROR, json)
        }
    }

    override fun updateTeamStatus(teamId: Long, status: Boolean): JSONObject {
        val json = JSONObject()
        return try {
            teamDao!!.updateTeamStatus(teamId, status)
            makeRes(SUCCESS_CODE, json)
        } catch (e: Exception) {
            json["msg"] = e.printStackTrace()
            makeRes(UPDATE_ERROR, json)
        }
    }

    override fun applyToTeam(apply: TeamApply): JSONObject {
        val json = JSONObject()
        try {
            val res = teamDao!!.queryTeamMembers(apply.teamId)
            val filter = res.filter {
                it.uid == apply.uid
            }
            if (filter.isNotEmpty()) {
                return makeRes(INSERT_ERROR, json, "你已经是此队伍成员！")
            }
            val resLeader = teamDao.queryTeamAndLeader(apply.teamId)
            if (resLeader.first().belongUserId == apply.uid) {
                return makeRes(INSERT_ERROR, json, "你是此队伍的队长！")
            }
            teamDao.applyToTeam(apply)
            return makeRes(SUCCESS_CODE, json)
        } catch (e: Exception) {
            json["msg"] = e.printStackTrace()
            return makeRes(INSERT_ERROR, json)
        }
    }

    override fun queryUserTeam(uid: Long, owner: Long): JSONObject {
        val json = JSONObject()
        return try {
            val res = teamDao!!.queryUserTeam(owner)
            json["data"] = res
            makeRes(SUCCESS_CODE, json)
        } catch (e: Exception) {
            json["msg"] = e.printStackTrace()
            makeRes(SELECT_ERROR, json)
        }
    }

    override fun updateApplyToTeam(applyId: Long, pass: Boolean): JSONObject {
        val json = JSONObject()
        return try {
            teamDao!!.updateApplyToTeam(applyId, pass)
            if (pass) {
                val res = teamDao.queryApplyByID(applyId).first()
                teamDao.addTeamMemBer(res.teamId, res.uid, System.currentTimeMillis())
            }
            makeRes(SUCCESS_CODE, json)
        } catch (e: Exception) {
            json["msg"] = e.printStackTrace()
            makeRes(INSERT_ERROR, json)
        }
    }

    override fun queryApplyToMe(owner: Long): JSONObject {
        val json = JSONObject()
        return try {
            json["data"] = teamDao!!.queryApplyToMe(owner)
            makeRes(SUCCESS_CODE, json)
        } catch (e: Exception) {
            json["msg"] = e.printStackTrace()
            makeRes(SELECT_ERROR, json)
        }
    }

    override fun queryTeamDetail(uid: Long, teamId: Long): JSONObject {
        val json = JSONObject()
        return try {
            json["teamAndLeader"] = teamDao!!.queryTeamAndLeader(teamId).first()
            json["member"] = teamDao.queryTeamMembers(teamId)
            json["isCollected"] = teamDao.selectCollectionsByUserAndTeamId(uid, teamId).isNotEmpty()
            makeRes(SUCCESS_CODE, json)
        } catch (e: Exception) {
            json["msg"] = e.printStackTrace()
            makeRes(SELECT_ERROR, json)
        }
    }

    override fun searchMatch(matchName: String, lastId: Long): JSONObject {
        val json = JSONObject()
        return try {
            json["data"] = teamDao!!.searchMatchList(matchName, lastId)
            makeRes(SUCCESS_CODE, json)
        } catch (e: Exception) {
            json["msg"] = e.printStackTrace()
            makeRes(SELECT_ERROR, json)
        }
    }

    override fun queryTop5Team(uid: Long): JSONObject {
        val json = JSONObject()
        return try {
            if (uid == 0L) {
                json["notInSchoolData"] = teamDao!!.searchTop5TeamWithoutLogin()
                makeRes(SUCCESS_CODE, json)
            } else {
                json["inSchoolData"] = teamDao!!.searchTop5TeamInMySchool(uid)
                json["notInSchoolData"] = teamDao.searchTop5TeamNotInMySchool(uid)
                makeRes(SUCCESS_CODE, json)
            }
        } catch (e: Exception) {
            json["msg"] = e.message
            makeRes(SELECT_ERROR, json)
        }
    }

    override fun addTeamPageViews(teamId: Long): JSONObject {
        val json = JSONObject()
        return try {
            teamDao!!.addTeamPageViews(teamId)
            makeRes(SUCCESS_CODE, json)
        } catch (e: Exception) {
            json["msg"] = e.message
            e.printStackTrace()
            makeRes(INSERT_ERROR, json)
        }
    }

    override fun queryTeamCollections(uid: Long, lastCreateTime: Long): JSONObject {
        val json = JSONObject()
        return try {
            json["data"] = teamDao!!.selectCollectionsByUser(uid, lastCreateTime)
            makeRes(SUCCESS_CODE, json)
        } catch (e: Exception) {
            json["msg"] = e.message
            e.printStackTrace()
            makeRes(SELECT_ERROR, json)
        }
    }

    override fun addToTeamCollection(teamId: Long, uid: Long): JSONObject {
        val json = JSONObject()
        return try {
            teamDao!!.addToCollection(teamId, uid)
            makeRes(SUCCESS_CODE, json)
        } catch (e: Exception) {
            json["msg"] = e.message
            e.printStackTrace()
            makeRes(SELECT_ERROR, json)
        }
    }

    override fun deleteTeamCollection(uid: Long, teamId: Long): JSONObject {
        val json = JSONObject()
        return try {
            teamDao!!.deleteCollectionById(uid, teamId)
            makeRes(SUCCESS_CODE, json)
        } catch (e: Exception) {
            json["msg"] = e.message
            e.printStackTrace()
            makeRes(DELETE_ERROR, json)
        }
    }

    override fun addUserBan(uid: Long): JSONObject {
        val json = JSONObject()
        return try {
            teamDao!!.addUserBan(uid, System.currentTimeMillis())
            val messageJSONObject = JSONObject()
            messageJSONObject["type"] = "Account"
            messageJSONObject["data"] = true
            webSocketHandler!!.sendMessageToUser(uid.toString(), TextMessage(messageJSONObject.toString()))
            makeRes(SUCCESS_CODE, json)
        } catch (e: Exception) {
            json["msg"] = e.message
            e.printStackTrace()
            makeRes(SELECT_ERROR, json)
        }
    }

    override fun deleteUserBane(uid: Long): JSONObject {
        val json = JSONObject()
        return try {
            teamDao!!.deleteUserBanByUid(uid)
            makeRes(SUCCESS_CODE, json)
        } catch (e: Exception) {
            json["msg"] = e.message
            e.printStackTrace()
            makeRes(DELETE_ERROR, json)
        }
    }

    override fun searchSameSchoolTeam(uid: Long): JSONObject {
        val json = JSONObject()
        return try {
            json["data"] = teamDao!!.searchSameSchoolTeam(uid)
            makeRes(SUCCESS_CODE, json)
        } catch (e: Exception) {
            json["msg"] = e.message
            e.printStackTrace()
            makeRes(DELETE_ERROR, json)
        }
    }

    override fun searchNewCreateTeam(uid:Long,lastCreateTime: Long): JSONObject {
        val json = JSONObject()
        return try {
            json["data"] = teamDao!!.searchNewCreateTeam(uid,lastCreateTime)
            makeRes(SUCCESS_CODE, json)
        } catch (e: Exception) {
            json["msg"] = e.message
            e.printStackTrace()
            makeRes(DELETE_ERROR, json)
        }
    }
}